//
//  BYLoginView.m
//  School+
//
//  Created by Sean Sebastian on 4/26/16.
//  Copyright © 2016 Sean Sebastian. All rights reserved.
//

#import "BYLoginView.h"

// frameworks
#import "Masonry.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "MJExtension.h"

// extension
#import "NSString+BYDateAndString.h"

// model
#import "UserAccount.h"

@implementation BYLoginView


#pragma mark - 懒加载

- (UIButton *)signIn
{
    if (_signIn == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        btn.backgroundColor = [UIColor whiteColor];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:@"登陆" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(signInClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.alpha = 0.8f;
        _signIn = btn;
        
        return btn;
    }
    return _signIn;
}

- (UIButton *)signUp
{
    if (_signUp == nil) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
        [btn setBackgroundColor:[UIColor blackColor]];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.alpha = 0.8f;
        [btn setTitle:@"注册" forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(signUpClick:) forControlEvents:UIControlEventTouchUpInside];
        
        _signUp = btn;
        
        return btn;
    }
    return _signUp;
}

- (UITextField *)username
{
    if (_username == nil) {
        UITextField *username = [[UITextField alloc] init];
        username.placeholder = @"请输入用户名\email";
        username.backgroundColor = [UIColor whiteColor];
        username.alpha = 0.8f;
        username.borderStyle = UITextBorderStyleLine;
        _username = username;
        
        return username;
    }
    return _username;
}

- (UITextField *)password
{
    if (_password == nil) {
        UITextField *password = [[UITextField alloc] init];
        password.placeholder = @"请输入密码";
        password.secureTextEntry = YES;
        password.borderStyle = UITextBorderStyleLine;
        password.backgroundColor = [UIColor whiteColor];
        password.alpha = 0.8f;
        
        _password = password;
        
        return password;
    }
    
    return _password;
}

#pragma mark - 响应事件

- (void)signInClick:(UIButton *)sender
{
    if ([self.username.text isEqualToString:@""] || [self.password.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"用户名／密码不能为空！"];
        return;
    }else{
        
        // url：不需要编码(内部已经实现了)
        NSURL *url = [NSURL URLWithString:@"http://localhost/SchoolPlus/login.php"];
        
        // 请求字符串
        NSString *bodyStr = [NSString stringWithFormat:@"username=%@&password=%@",self.username.text,self.password.text];
        // request
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        // 设置请求方法
        request.HTTPMethod = @"POST";
        // 设置请求体
        // HTTPBody  用的比较多
        // HTTPBody 和 HTTPBodyStream 只需要设置一个就够了
        request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
        //    request.HTTPBodyStream = [[NSInputStream alloc] initWithData:[bodyStr dataUsingEncoding:NSUTF8StringEncoding]];
        // 发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
            
            NSLog(@"%@--%@",response,result);
            
            // 处理时间
            NSDate *date = [NSString dateFromString:result[@"createTime"]];
            // result[@"name"]有值就说明密码正确
            if (result[@"name"]) {
                [SVProgressHUD showSuccessWithStatus:@"登陆成功，在控制器中跳转页面"];
                // 数据保存到模型中
                // 使用MJExtension
                NSDictionary *dict = @{
                                       @"username":result[@"name"],
                                       @"password":result[@"password"],
                                       @"email":result[@"email"],
                                       @"iconImageURL":result[@"iconImageURL"],
                                       @"createTime":date,
                                       @"userID":result[@"id"]
                                       };
                [UserAccount mj_objectWithKeyValues:dict];
                [[UserAccount sharedUserAccount] saveUserInfo];
                
                [self.delegate loginViewLoginClick];        
            }else{
                [SVProgressHUD showErrorWithStatus:result[@"errorMessage"]];
                return ;
            }
        }];
        
        
    }
}

- (void)signUpClick:(UIButton *)sender
{
    [self.delegate loginViewRegistClick];
}


- (void)prepareUI
{
    
    [self addSubview:self.backgroundImageView];
    [self addSubview:self.username];
    [self addSubview:self.password];
    [self addSubview:self.signIn];
    [self addSubview:self.signUp];
    
    [self.backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self).insets(UIEdgeInsetsMake(0,0,0,0));
    }];
    
    [self.username mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.left.equalTo(self).with.offset(35);
        make.right.equalTo(self).with.offset(-35);
        make.top.equalTo(self).with.offset(100);
        make.height.mas_equalTo(@46);
    }];
    [self.password mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.username);
        make.height.equalTo(self.username);
        make.width.equalTo(self.username);
        make.top.equalTo(self.username.mas_bottom).with.offset(20);
    }];
    
    [self.signIn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.password);
        make.width.equalTo(self.signUp);
        make.height.mas_equalTo(@40);
        make.top.equalTo(self.password.mas_bottom).with.offset(20);
        make.right.equalTo(self.signUp.mas_left).with.offset(-30);
    }];
    [self.signUp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.signIn);
        make.height.equalTo(self.signIn);
        make.right.equalTo(self.password);
        make.top.equalTo(self.signIn);
        
    }];
}

- (UIImageView *)backgroundImageView
{
    if (_backgroundImageView == nil) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"userLogin"]];
        _backgroundImageView = imageView;
        return imageView;
    }
    return _backgroundImageView;
}

// override initialization method
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self prepareUI];
        
    }
    return self;
}


@end